package com.sd365.permission.centre.service.impl;

import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.entity.Resource;
import com.sd365.permission.centre.pojo.vo.ResourceVO;
import com.sd365.permission.centre.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author No_one
 * @description 根据资源生成菜单
 */
@Slf4j
@Service
public class MenuServiceImpl extends AbstractBaseDataServiceImpl implements MenuService {

    @Override
    public List<ResourceVO>  buildMenu(List<Resource> resourceList) {
        ResourceVO resourceVO = null;
        List<ResourceVO> resourceVOS=new ArrayList<>();
        for(Resource resource : resourceList) {
            if(resource.getParentId() == -1) {
                System.out.println(resource == null);
                resourceVO = BeanUtil.copy(resource, ResourceVO.class);
                resourceVOS.add(resourceVO);
            }
        }
        int size=resourceVOS.size();
        for(int index=0;index<size;index++){
            recBuildMenu(resourceVOS.get(index), resourceList);
        }
       // recBuildMenu(resourceVO, resourceList);
        return resourceVOS;
    }

    public void recBuildMenu(ResourceVO resourceVO, List<Resource> resourceList) {

        Long id = resourceVO.getId();
        List<ResourceVO> subList = new LinkedList<>();

        // 查找资源列表里的子资源
        // 检验是否查询结束，递归结束
        boolean flag = true;
        for(Resource resource : resourceList) {
            if(resource.getParentId().equals(id)) {
                flag = false;
                ResourceVO subResourceVO = null;
                // copy resource to subResourceVO
                subResourceVO = BeanUtil.copy(resource, ResourceVO.class);
                subList.add(subResourceVO);
                // resourceList.remove(resource);
            }
        }
        // 该资源没有子资源，递归结束
        if(flag) {
            resourceVO.setResourceVOs(null);
            return;
        }

        resourceVO.setResourceVOs(subList);

        for(ResourceVO resourceVO1 : subList) {
            recBuildMenu(resourceVO1, resourceList);
        }
    }
}
